<?php
class Model{
    
    //保存链接信息
    public static $link = NULL;
    //保存表名
    protected $table = NULL;
    //初始化表信息
    private $opt;
    //记录发送的sql
    public static $sqls = array();

    public function __construct($table = NULL){
         
         $this->table = is_null($table) ? C('DB_PREFIX') . $this->table : C('DB_PREFIX') . $table;
         //echo $this->table;
         //链接数据库
    	 $this->_connect();
    	 //初始化sql信息
    	 $this->_opt();

    }

    public function query($sql){
          self::$sqls[] = $sql;
          $link = self::$link;
          $result = $link->query($sql);
          if($link->errno) P('mysql错误' . $link->error . '<br/>SQL:' . $sql);    
           $rows = array();
           while ($row = $result->fetch_assoc()) {
           	  $rows[] = $row;
           }
           $result->free();
           $this->_opt();
           return $rows;
    }

    public function all(){
    	$sql = " SELECT " . $this->opt['field'] . " FROM " . $this->table . $this->opt['where'] . $this->opt['group'] . $this->opt['having'] . $this->opt['order'] . $this->opt['limit'];
    	return $this->query($sql);
    }

    public function findAll(){
    	return $this->all();
    }

    public function field($field){
         $this->opt['field'] = $field;
         return $this;
    }

    public function where($where) {
    	 $this->opt['where'] = " WHERE " . $where;
         return $this;
    }

    public function order($order){
    	$this->opt['order'] = " ORDER BY " . $order;
         return $this;
    }

    public function limit($limit){
    	$this->opt['limit'] = " LIMIT " . $limit;
         return $this;
    }

    public function find(){
    	$data = $this->limit(1)->all();
    	$data = current($data);  //把二维数组变成一维数组
    	return $data;
    }

    public function one(){
    	return $this->find();
    }

    private function _opt(){
    	$this->opt = array(
              'field'  => '*',
              'where'  => '',
              'group'  => '',
              'having' => '',
              'order'  => '',
              'limit'  => ''
    		);
    }

     //链接数据库
    private function _connect(){
        if(is_null(self::$link)){
        	$db = C('DB_DATABASE');
        	if(empty($db)) P('请先配置数据库！！！');
        	$link = new Mysqli(C('DB_HOST'),C('DB_USER'),C('DB_PASSWORD'),$db,C('DB_PORT'));
        	if($link->connect_error) P('数据库连接错误，请检查配置项');
        	$link->set_charset(C('DB_CHARSET'));
        	self::$link = $link;
        }
    }

    public function exe($sql){
        self::$sqls[] = $sql;
        $link = self::$link;
        $bool = $link->query($sql);
        $this->_opt();
        if (is_object($bool)) {
        	P('请用query方法发送查询sql');
        }

        if($bool){
        	return $link->insert_id ? $link->insert_id : $link->affected_rows;
        } else {
        	P('sql错误：' . $link->error . '<br/>SQL:' . $sql);
        }

    }

    public function add($data = NULL){
      if(is_null($data))  $data = $_POST;
      //P($data);exit();
      $fields = '';
      $values = '';
      foreach ($data as $f => $v) {
        $fields .= "`" . $this->_safe_str($f) . "`,";
        $values .= "'" . $this->_safe_str($v) . "',";
      }       
      $fields = trim($fields,',');
      $values = trim($values,',');
      //insert into goods (`name`,`age`) values ('ma','323');
      $sql = "INSERT INTO " . $this->table . '(' . $fields . ') VALUES ( ' . $values . ')';
      return $this->exe($sql);
    } 

    public function update($data = NULL){
        if(empty($this->opt['where']))  P('更新操作必须有where条件');
        if(is_null($data))  $data = $_POST;
        //UPDATE goods SET `name`='21',`age`='21' WHERE id=1
        $values = '';
        foreach ($data as $f => $v) {
           $values .= "`" . $this->_safe_str($f) . "`='" . $this->_safe_str($v) . "',";
         } 

         $values = trim($values,',');
         //echo $values;
         $sql = "UPDATE " . $this->table ." SET " . $values . $this->opt['where']; 
         //echo "$sql";

         return $this->exe($sql);
    }

    public function delete(){
    	if(empty($this->opt['where']))  P('删除语句必须有where条件');
    	$sql = "DELETE FROM " . $this->table . $this->opt['where'];
    	return $this->exe($sql);
    }

    //数据库安全处理  防注入等
    private function _safe_str($str){
         if(get_magic_quotes_gpc()){
           $str = stripslashes($str);
         }
         return self::$link->real_escape_string($str);
    }
}



?>